import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Alert, Form, Input, Icon, Button } from 'antd';

import styles from './Login.less';

@connect()
@Form.create()
class Login extends React.Component {
  state = {
    submitting: false,
    errMsg: '',
  };

  handleSubmit = () => {
    const { form, dispatch } = this.props;
    form.validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }
      this.setState({ submitting: true, errMsg: '' });
      dispatch({
        type: 'auth/login',
        payload: values,
      }).then(resp => {
        if (resp.code === 0) {
          this.setState({ submitting: false });
          router.push('/');
        } else {
          this.setState({ errMsg: resp.message, submitting: false });
        }
      })
    })
  };

  render() {
    const { submitting, errMsg } = this.state;
    const { form: { getFieldDecorator } } = this.props;
    return (
      <div className={styles.main}>
        {errMsg && <Alert style={{ marginBottom: 24 }} message={errMsg} type="error" showIcon />}
        <Form className="login-form">
          <Form.Item>
            {getFieldDecorator('username', {
              rules: [{ required: true, message: '请输入用户名!' }],
            })(
              <Input
                size="large"
                prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="用户名"
              />,
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('password', {
              rules: [{ required: true, message: '请输入密码!' }],
            })(
              <Input.Password
                size="large"
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                placeholder="密码"
              />,
            )}
          </Form.Item>
          <Form.Item>
            <Button type="primary" size="large" block loading={submitting} onClick={this.handleSubmit}>
              登 录
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default Login;
